//app.js
App({

  // 小程序全局参数
  globalData: {
    host: "https://qssh.vshop365.cn/api/", //全局API
    net_error: "网络不可用，请重试！",
  },

  onLaunch: function(option) {
    var that = this
    var pid = '0';
    if (option.query.pid) {
      pid = option.query.pid
    }
    var scene = option.scene;
    // console.log('pid==' + pid)
    // console.log('scene==' + scene)
    wx.login({
      success: (res) => {
        var code = res.code;
        wx.request({
          url: that.globalData.host + 'login/login',
          data: {
            code, pid, scene
          },
          success: (res) => {
            // console.log(res)
            // 存session_key
            wx.setStorageSync('session_key', res.data.data.session_key);
            // 存openid
            wx.setStorageSync('openid', res.data.data.openid);
            // 存user_id
            wx.setStorageSync('userId', res.data.data.userId || '0');
            wx.request({
              url: that.globalData.host + 'index/addView',
              data: {
                user_id: res.data.data.userId
              },
              success: (res) => {
                
              }
            })
          }
        })
      }
    })
  },

  // 点击事件无请求，但需要验证登录态时触发
  confirmLogin: function(_else) {
    var that = this;
    var isLogin = wx.getStorageSync('isLogin') || false;
    if (isLogin == false) {
      wx.showModal({
        content: '请先登录后操作！',
        success: (res) => {
          if (res.confirm) {
            console.log(777)
            wx.navigateTo({
              url: '/pages/login/login',
            })
          }
        }
      })
    } else {
      _else()
    }
  },


  //** url  请求路径
  //** Data	请求参数
  //** Checklogin	是否需要登录：true需要登录,false不需要登录
  //** Success  成功后回调函数
  //** Fail     失败后回调函数
  //** Complete 完成后回调函数

  request(url, data, method, check_login, success, fail, complete) {
    let that = this;
    //验证是否要登录
    // console.log(check_login)
    if (check_login) {
      var isLogin = wx.getStorageSync('isLogin');
      if (!isLogin) {
        // console.log(1111111)
        wx.hideLoading();
        wx.showModal({
          title: '温馨提示',
          content: '请授权后进行操作！',
          showCancel: true,
          success: function(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/login/login'
              })
            }
          },
          fail: function(res) {},
          complete: function(res) {},
        })

      } else {
        that._request(url, data, method, success, fail, complete);
      }
    } else {
      that._request(url, data, method, success, fail, complete);
    };

  },

  _request: function(url, data, method, _success, _fail, _complete) {
    wx.request({
      url: url,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: method,
      data: data,
      success(res) {
        wx.hideLoading();
        if (res.statusCode == 200) {
          _success(res)
        } else {
          _fail(res)
        }
      },
      fail(res) {
        wx.hideLoading();
        _fail(res)
      },
      complete(res) {
        // wx.hideLoading();
        _complete(res)
      },
    });
  },

  // 获取formid
  getFormId: function(formId) {
    var that = this;
    console.log('formId==' + formId);
    wx.request({
      url: that.globalData.host + 'common/saveformid',
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        openid: wx.getStorageSync('openid'),
        formid: formId
      },
      success: function(res) {
        console.log(res)
      }
    })
  },

  /**
    * 上传图片
    */
  uploadImage(sumNumber, add_img, callback) {
    var that = this;
    add_img || []  //已上传图片数组
    //sumNumber 允许上传的总数量
    var photoNum = sumNumber - add_img.length; //剩余可上传数
    if (photoNum == 0) {
      wx.showToast({
        title: `最多上传${sumNumber}张图片`,
        icon: 'none',
        duration: 1500,
      })
      return;
    }
    wx.chooseImage({
      count: photoNum,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res)
        // tempFilePath可以作为img标签的src属性显示图片
        let tempFilePaths = res.tempFilePaths
        let temLength = tempFilePaths.length;
        // let { add_img } = that.data; //已上传图片数组
        let number = 0;
        for (let i = 0, h = temLength; i < h; i++) {
          wx.showLoading({
            title: '上传中',
            mask: true,
          })
          wx.uploadFile({
            url: that.globalData.host + 'common/uploadimg',
            filePath: tempFilePaths[i],
            name: 'file',
            success: function (res) {
              console.log(res)
              number++;
              if (number == h) {
                wx.hideLoading();
              }
              res = JSON.parse(res.data);
              add_img.push(res.filesrc);
              // that.setData({
              //   add_img: add_img,
              // })
              callback && callback(add_img)
            },
            fail: function (err) { console.log(err) },
            complete: function (res) { },
          })
        }
      }
    })
  },



})